<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      nav {
        width: 100vw;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.5);
        position: fixed;
        display: none;
      }
      * {
        margin: 0;
        padding: 0;
      }
      .active {
        display: block;
      }
      img {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
      input {
        outline: none;
      }
    </style>
  </head>
  <body>
    <nav>
      <img src="Iphone-spinner-2(1).gif" alt="" />
    </nav>
    <form>
      用户名： <input type="text" id="text" /> <br />
      密码： <input type="text" id="password" /> <br />
      <button type="button">登录</button>
    </form>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let input = document.querySelector("#text");
      let password = document.querySelector("#password");
      let button = document.querySelector("button");
      const nav = document.querySelector("nav");
      //封装axios实例
      const instance = axios.create({
        baseURL: "http://49.235.98.65:3000/",
        timeout: 5000,
      });
      //   请求拦截器
      instance.interceptors.request.use(
        (request) => {
          return request;
        },
        function (error) {
          // 对请求错误做些什么
          return Promise.reject(error);
        }
      );

      // ? 响应拦截器
      instance.interceptors.response.use(
        function (response) {
          return response.data;
        },
        function (error) {
          return Promise.reject(error);
        }
      );
      //   执行函数
      button.onclick = async function () {
        try {
          nav.classList.add("active");
          const request = await instance.post("/user/login", {
            username: input.value,
            password: password.value,
          });
          const key = request.user.token;
          localStorage.setItem("key", key);
          nav.classList.remove("active");
          alert("登录成功");
        } catch {
          alert("登录失败");
        } finally {
          nav.classList.remove("active");
          input.value = "";
          password.value = "";
        }
      };
    </script>
  </body>
</html>
